package com.zxy.ziems.server.device.pojo.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zxy.ziems.server.device.pojo.entity.DataTypeEntity;
import com.zxy.ziems.server.device.pojo.entity.DataUnitEntity;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;

/**
 * 数据单元
 * @author 10348359
 * @create 2024-03-20 11:29
 */
@Data
public class DataUnitDTO {
    /**
     * 主键
     */
    @NotBlank(message = "主键不能为空", groups = {Select.class})
    private String id;
    /**
     * 编号
     */
    @NotBlank(message = "编号不能为空", groups = {Add.class, Update.class})
    private String code;
    /**
     * 描述
     */
    @NotBlank(message = "名称不能为空", groups = {Add.class, Update.class})
    private String name;

    /**
     * 倍率 默认为1
     */
    private Integer multiple = 1;

    /**
     * 除数 默认为1
     */
    private Integer divisor = 1;

    /**
     * 最后分组名称
     */
    @Size(max = 5, min = 1, message = "分组层级要在1——5级内", groups = {Add.class, Update.class})
    private List<String> groupNameList;

    public interface Add{}
    public interface Update{}
    public interface Select {}

    @JsonIgnore
    public DataUnitEntity buildEntity() {
        DataUnitEntity entity = new DataUnitEntity();
        entity.setCode(code);
        entity.setName(name);
        entity.setId(id);
        entity.setDivisor(divisor);
        entity.setMultiple(multiple);

        List<BiConsumer<DataUnitEntity, String>> setList = Arrays.asList(
                DataUnitEntity::setGroupLevel1Name,
                DataUnitEntity::setGroupLevel2Name,
                DataUnitEntity::setGroupLevel3Name,
                DataUnitEntity::setGroupLevel4Name,
                DataUnitEntity::setGroupLevel5Name);

        int s1 = setList.size(), s2 = Objects.nonNull(groupNameList) ? groupNameList.size(): 0;
        for (int i = 0, size = Math.min(s1, s2); i < size; i++) {
            String s = groupNameList.get(i);
            BiConsumer<DataUnitEntity, String> field = setList.get(i);
            field.accept(entity, s);
            if (i == size - 1) {
                entity.setGroupName(s);
            }
        }
        return entity;
    }
}
